import editor from '../model/editor';
import {
    getcellvalue
} from '../model/getdata';
import {
    luckysheetrefreshgrid
} from '../view/refresh';
import {
    selectionCopyShow
} from '../view/select';
import {
    genarate
} from '../utils/format';
import {
    replaceHtml,
    getObjType
} from '../utils/util';
import Store from '../store';

export {
    clearcopy,
    copy,
    pasteHandler,
    doPaste,
};

// Paste data from excel
function doPaste(e) {
    let clipboardData = window.clipboardData; //for IE
    if (!clipboardData) { // for chrome
        clipboardData = e.originalEvent.clipboardData;
    }

    let txtdata = clipboardData.getData("text/html");

    if (txtdata.indexOf("table") > -1) {
        $("#luckysheet-copy-content").html(txtdata);

        let data = new Array($("#luckysheet-copy-content").find("table tr").length);
        let colLen = 0;
        $("#luckysheet-copy-content").find("table tr").eq(0).find("td").each(function () {
            let colspan = parseInt($(this).attr("colspan"));
            if (isNaN(colspan)) {
                colspan = 1;
            }
            colLen += colspan;
        });

        for (let i = 0; i < data.length; i++) {
            data[i] = new Array(colLen);
        }

        let r = 0;
        $("#luckysheet-copy-content").find("table tr").each(function () {
            let $tr = $(this);
            let c = 0;
            $tr.find("td").each(function () {
                let $td = $(this);
                let cell = {};
                let txt = $td.text();

                if ($.trim(txt).length == 0) {
                    cell.v = null;
                    cell.m = "";
                } else {
                    let mask = genarate($td.text());
                    cell.v = mask[2];
                    cell.ct = mask[1];
                    cell.m = mask[0];
                }

                let bg = $td.css("background-color");
                if (bg == "rgba(0, 0, 0, 0)") {
                    bg = null;
                }

                cell.bg = bg;


                if (data[r][c] == null) {
                    data[r][c] = cell;
                    let rowspan = parseInt($td.attr("rowspan"));
                    let colspan = parseInt($td.attr("colspan"));

                    if (isNaN(rowspan)) {
                        rowspan = 1;
                    }

                    if (isNaN(colspan)) {
                        colspan = 1;
                    }

                    let r_ab = Store.luckysheet_select_save[0]["row"][0] + r;
                    let c_ab = Store.luckysheet_select_save[0]["column"][0] + c;

                    if (rowspan > 1 || colspan > 1) {
                        let first = {
                            "rs": rowspan,
                            "cs": colspan,
                            "r": r_ab,
                            "c": c_ab
                        };
                        data[r][c].mc = first;
                    }
                }

                c++;

                if (c == colLen) {
                    return true;
                }
            });

            r++;
        });
        pasteHandler(data);
        $("#luckysheet-copy-content").empty();
    }

}

function clearcopy(e) {
    let clipboardData = window.clipboardData; //for IE
    if (!clipboardData) { // for chrome
        if (!!e) {
            clipboardData = e.originalEvent.clipboardData;
        }
    }
    let cpdata = " ";

    Store.luckysheet_selection_range = [];
    selectionCopyShow();

    if (!clipboardData) {
        let textarea = $("#luckysheet-copy-content").css("visibility", "hidden");
        textarea.val(cpdata);
        textarea.focus();
        textarea.select();
        // 等50毫秒，keyPress事件发生了再去处理数据
        setTimeout(function () {
            textarea.blur().css("visibility", "visible");
        }, 10);
    } else {
        clipboardData.setData('Text', cpdata);
        return false; //否则设不生效
    }
};

function copy(e) { //copy事件
    let clipboardData = window.clipboardData; //for IE
    if (!clipboardData) { // for chrome
        clipboardData = e.originalEvent.clipboardData;
    }

    Store.luckysheet_selection_range = [];
    //copy范围
    let rowIndexArr = [],
        colIndexArr = [];
    let copyRange = [],
        RowlChange = false,
        HasMC = false;

    for (let s = 0; s < Store.luckysheet_select_save.length; s++) {
        let range = Store.luckysheet_select_save[s];

        let r1 = range.row[0],
            r2 = range.row[1];
        let c1 = range.column[0],
            c2 = range.column[1];

        for (let copyR = r1; copyR <= r2; copyR++) {
            if (Store.config["rowhidden"] != null && Store.config["rowhidden"][copyR] != null) {
                continue;
            }

            if (!rowIndexArr.includes(copyR)) {
                rowIndexArr.push(copyR);
            }

            if (Store.config["rowlen"] != null && (copyR in Store.config["rowlen"])) {
                RowlChange = true;
            }

            for (let copyC = c1; copyC <= c2; copyC++) {
                if (Store.config["colhidden"] != null && Store.config["colhidden"][copyC] != null) {
                    continue;
                }

                if (!colIndexArr.includes(copyC)) {
                    colIndexArr.push(copyC);
                }

                let cell = Store.flowdata[copyR][copyC];

                if (getObjType(cell) == "object" && ("mc" in cell) && cell.mc.rs != null) {
                    HasMC = true;
                }
            }
        }

        Store.luckysheet_selection_range.push({
            "row": range.row,
            "column": range.column
        });
        copyRange.push({
            "row": range.row,
            "column": range.column
        });
    }

    selectionCopyShow();

    //luckysheet内copy保存
    Store.luckysheet_copy_save = {
        "dataSheetIndex": Store.currentSheetIndex,
        "copyRange": copyRange,
        "RowlChange": RowlChange,
        "HasMC": HasMC
    };

    //copy范围数据拼接成table 赋给剪贴板
    let _this = this;

    let cpdata = "",
        d = editor.deepCopyFlowData(Store.flowdata);
    let colgroup = "";


    for (let i = 0; i < rowIndexArr.length; i++) {
        let r = rowIndexArr[i];

        if (Store.config["rowhidden"] != null && Store.config["rowhidden"][r] != null) {
            continue;
        }

        cpdata += '<tr>';

        for (let j = 0; j < colIndexArr.length; j++) {
            let c = colIndexArr[j];

            if (Store.config["colhidden"] != null && Store.config["colhidden"][c] != null) {
                continue;
            }

            let column = '<td ${span} style="${style}">';

            if (d[r] != null && d[r][c] != null) {
                let style = "",
                    span = "";

                if (r == rowIndexArr[0]) {
                    if (Store.config == null || Store.config["columnlen"] == null || Store.config["columnlen"][c.toString()] == null) {
                        colgroup += '<colgroup width="72px"></colgroup>';
                    } else {
                        colgroup += '<colgroup width="' + Store.config["columnlen"][c.toString()] + 'px"></colgroup>';
                    }
                }

                if (c == colIndexArr[0]) {
                    if (Store.config == null || Store.config["rowlen"] == null || Store.config["rowlen"][r.toString()] == null) {
                        style += 'height:19px;';
                    } else {
                        style += 'height:' + Store.config["rowlen"][r.toString()] + 'px;';
                    }
                }

                let reg = /^(w|W)((0?)|(0\.0+))$/;
                let c_value;
                if (d[r][c].ct != null && d[r][c].ct.fa != null && d[r][c].ct.fa.match(reg)) {
                    c_value = getcellvalue(r, c, d);
                } else {
                    c_value = getcellvalue(r, c, d, "m");
                }


                column = replaceHtml(column, {
                    "style": style,
                    "span": span
                });

                if (c_value == null) {
                    c_value = getcellvalue(r, c, d);
                }

                if (c_value == null) {
                    c_value = "";
                }

                column += c_value;
            } else {
                let style = "";


                column += "";

                if (r == rowIndexArr[0]) {
                    if (Store.config == null || Store.config["columnlen"] == null || Store.config["columnlen"][c.toString()] == null) {
                        colgroup += '<colgroup width="72px"></colgroup>';
                    } else {
                        colgroup += '<colgroup width="' + Store.config["columnlen"][c.toString()] + 'px"></colgroup>';
                    }
                }

                if (c == colIndexArr[0]) {
                    if (Store.config == null || Store.config["rowlen"] == null || Store.config["rowlen"][r.toString()] == null) {
                        style += 'height:19px;';
                    } else {
                        style += 'height:' + Store.config["rowlen"][r.toString()] + 'px;';
                    }
                }

                column = replaceHtml(column, {
                    "style": style,
                    "span": ""
                });
                column += "";
            }

            column += '</td>';
            cpdata += column;
        }

        cpdata += "</tr>";
    }
    cpdata = '<table data-type="luckysheet_copy_action_table">' + colgroup + cpdata + '</table>';

    Store.iscopyself = true;

    if (!clipboardData) {
        var oInput = document.createElement('input');
        oInput.setAttribute('readonly', 'readonly');
        oInput.value = cpdata;
        document.body.appendChild(oInput);
        oInput.select(); // 选择对象
        document.execCommand("Copy");
        oInput.style.display = 'none';
        document.body.removeChild(oInput);
    } else {
        clipboardData.setData('Text', cpdata);
        return false; //否则设不生效
    }


    setTimeout(function () { // got focus and then press esc cancel copy style
        $("#luckysheet-rich-text-editor").focus().select();
    }, 50);
};

function pasteHandler(data) {

    if (Store.luckysheet_select_save.length > 1) {
        alert("不能对多重选择区域执行此操作，请选择单个区域，然后再试");
    }

    if (data.length == 0) {
        return;
    };

    let copyh = data.length,
        copyc = data[0].length;

    let minh = Store.luckysheet_select_save[0].row[0], //应用范围首尾行
        maxh = minh + copyh - 1;
    let minc = Store.luckysheet_select_save[0].column[0], //应用范围首尾列
        maxc = minc + copyc - 1;

    let d = editor.deepCopyFlowData(Store.flowdata); //取数据

    //若应用范围超过最大行或最大列，增加行列

    for (let h = minh; h <= maxh; h++) {
        let x = [].concat(d[h]);

        for (let c = minc; c <= maxc; c++) {

            let value = null;
            if (data[h - minh] != null && data[h - minh][c - minc] != null) {
                value = data[h - minh][c - minc];
            }

            x[c] = $.extend(true, {}, value);

        }
        d[h] = x;

    }
    Store.flowdata = d;
    luckysheetrefreshgrid();

}